'use strict';
import React from 'react';
import {AutoComplete, Button, Form, Input, InputNumber, notification, Popconfirm, Select, Table} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import UploadPic from "../../../components/UploadPic";
import ViewTitle from "../../../components/ViewTitle";
import ModalSelectSalesProds from "./ModalSelectSalesProds";
import styles from "../../index.less";


moment.locale('zh-cn');
const EditableContext = React.createContext();

const EditableRow = ({form, index, ...props}) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const columns = [
  {title: '订单编码', dataIndex: 'salesOrderCode', key: 'salesOrderCode'},
  {title: '商品名称', dataIndex: 'prodName', key: 'prodName'},
  {title: '商品编号', dataIndex: 'prodCode', key: 'prodCode'},
  {title: '商品单价', dataIndex: 'price', key: 'price'},
  {title: '开票商品数量', dataIndex: 'count', key: 'count', editable: true},
  {
    title: '商品金额', dataIndex: 'count', key: 'count', render: (value, record) => {
      const {price = 0, count = 0} = record;
      return <div>{price * count}</div>;
    }
  },
  {title: '销售公司', dataIndex: 'division', key: 'division'},
  {title: '客户', dataIndex: 'customer', key: 'customer'},

  {
    title: '创建时间', dataIndex: 'createdTs', key: 'createdTs', render: value => {
      return <div>{moment(value).format('YYYY-MM-DD')}</div>;
    }
  },
];

const EditableFormRow = Form.create()(EditableRow);
@Form.create()
@connect(({
            tenant,
            global,
            vendor,
            dic, finance, dict, customer
          }) => ({...tenant, ...dic, ...vendor, ...global, ...finance, ...dict, ...customer}))
export default class ModalCreateOrEditInvoiceRecord extends FormBase {
  constructor(props) {
    super(props);
    const {record} = this.props;
    this.state = {...record};

  }

  componentDidMount() {
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'vendor/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
  }


  renderFoot = () => {
    const {foot, value, callback, modalRef, record, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              const {name, code, fileList, records} = this.state;
              values.recordId = record ? record.recordId : undefined;
              values.name = name;
              values.code = code;
              values.fileList = fileList;
              values.records = records;
              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  handleSave = row => {
    const newData = [...this.state.records];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row
    });
    this.setState({records: newData});
  };


  render() {
    const {form,  divisionDict = [], customers = [], type} = this.props;
    let {fileList, name, invoiceNumber, division, taxRate, records = []} = this.state;
    const divisionName ='销售公司' ;
    const tableTitle =  '开票商品列表';
    let amount = 0;
    _.map(records, item => {
      const {price, count} = item;
      amount += price * count;
    });
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell
      }
    };
    const cols = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      };
    });
    cols.push( {
      title: '操作', dataIndex: 'opt', key: 'opt', fixed: 'right', render: (value,record) => {
        const {spLotId} = record;
        return <div>
          {<Popconfirm
            title="确认删除"
            onConfirm={() => {
              const {records} = this.state;
              const temp = [];
              _.map(records, item => {
                if (item.spLotId !== spLotId) {
                  temp.push(item);
                }
              });
              this.state.records = temp;
              this.componentDidMount();
            }}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>}
        </div>;
      }
    })
    return (
      <Form>
        {<FormLayout form={form} cols={2}>
          <FormField
            label={'客户'}
            name={'name'}
            initialValue={name}
            required={true}
          >
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getCustomerOpt(customers )}
                          allowClear
                          onChange={value => {
                            if (!value) {
                              this.state['name'] = '';
                              this.state['code'] = '';
                            }
                          }}
                          onSelect={(value, option) => {
                            const {key, props} = option;
                            this.state['code'] = key;
                            this.state['name'] = value;
                          }}

            >
            </AutoComplete>
          </FormField>
          <FormField
            label={divisionName}
            name={'division'}
            initialValue={division}
            required={true}
          >
            <Select allowClear>{this.getDivision(divisionDict)}</Select>
          </FormField>
          <FormField
            label={'发票号'}
            name={'invoiceNumber'}
            initialValue={invoiceNumber}
            required={true}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'开票金额'}
            name={'amount'}
            initialValue={amount}
            required={true}
          >
            <InputNumber disabled style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'税率'}
            name={'taxRate'}
            initialValue={taxRate}
            required={true}
          >
            <Select allowClear style={{width: '100%'}}>
              {this.getSelectOption(this.taxRateOption1)}
            </Select>
          </FormField>
        </FormLayout>
        }
        {<ViewTitle title={tableTitle} actions={<Button type={'primary'} onClick={() => {
          ModalView.open(ModalSelectSalesProds, {
            title: "选择订单商品",
            width: '1180px'
          }, {
            type,
            callback: (_prods) => {
              const {records = []} = this.state;
              if (records.length === 0) {
                this.state.records = [];
              }
              console.log('llll',_prods)
              this.state.records.push(..._prods);
              this.componentDidMount();
            }
          })
        }}>选择</Button>}></ViewTitle>}

        <Table
          className={styles.antTable}
          rowClassName={() => 'editable-row'}
          components={components}
          bordered={true}
          columns={cols}
          dataSource={records}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          //  scroll={{ x: 1300 }}
        ></Table>


        <UploadPic title={'上传发票'} fileList={fileList} callback={f => this.state.fileList = f.fileList}></UploadPic>

        {this.renderFoot()}
      </Form>
    );
  }
}

class EditableCell extends React.Component {
  state = {
    editing: false
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({editing}, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const {record, handleSave} = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({...record, ...values});
    });
  };

  renderCell = form => {
    this.form = form;
    const {children, dataIndex, record, title} = this.props;
    const {editing} = this.state;
    return editing ? (
      <Form.Item style={{margin: 0}}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`
            }
          ],
          initialValue: record[dataIndex]
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{paddingRight: 24}}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}
